package Grantsfire::Controller::Admin;
use strict;
use warnings;
use base 'Catalyst::Controller';

sub begin : Private {
    my ( $self, $c ) = @_;

    $c->authorization_required( realm => "Grantsfire Admin" );
    $c->authorization_required_response( realm => "Grantsfire Admin" ) unless $c->user and $c->user->id eq 'admin';

    $c->forward('/begin');
}

sub default : Private {
    my ( $self, $c ) = @_;

    my $rs = $c->model('GF::Feed')->search(
        undef,
        {order_by=>'created DESC', rows=>10})->page(1);
    $c->stash->{feeds} = [$rs->all];
    $c->stash->{feedpager} = $rs->pager;
}

sub orgadd : Regex("^admin/org/add$") {
    my ( $self, $c ) = @_;

    eval {
        $c->check_params([
                url => [qw(NOT_BLANK HTTP_URL)],
                org => [qw(NOT_BLANK)],
            ]);
        die "This organization already exists\n" if $c->model('GF::Org')->search(
                {
                    'vcard.url' => $c->req->params->{url}
                },
                {
                    join => [qw/vcard/],
                },
            )->first;
        $c->model('GF::Org')->create({
            vcard => $c->model('GF::Vcard')->create({
                url => $c->req->params->{url}, 
                org => $c->req->params->{org},
                fn => $c->req->params->{org},
            })->id,
        });
    };
    if ($@) {
        $c->error($@);
    }
    $c->redirect_success('Organization added.');
}

sub orgremove : Regex("^admin/org/remove$") {
    my ( $self, $c, $org_id) = @_;
    eval {
        my $org = $c->model('GF::Org')->find($org_id);
        $org->delete;
    };
    if ($@) {
        $c->error($@);
    }
    $c->redirect_success('Organization deleted.');
}

1;
